var _datatable_form = function (o, dt, param, data, type) {

    // jquery el
    var el = this;
    var elIndex = el.prevAll().length;
    var ajaxLock = false;
    var url = el.attr('href');
    var modalEl = $('#datatable-popup');
    var boxEl = modalEl.find('#datatable-popup-body>.popup-block');
    var prevEl = modalEl.find('.datatable-popup-prev').unbind();
    var nextEl = modalEl.find('.datatable-popup-next').unbind();
    var buttonEl = modalEl.find('.js-datatable-save');
    var closeEl = modalEl.find('.btn-close');
    var autoClose = false;
    var formEl;
    var popupId;

    // 查找上一条／下一条记录位置
    var ptr = el.closest('tr');
    var prevLength = ptr.prevAll().length;
    var nextLength = ptr.nextAll().length;
    var index = ptr.prevAll().length;

    // 切换到上一条／下一条
    var call = function (dir) {
        var _data = o._table.row(index + dir).data();
        var datac = {};
        var el = o._tableEle.find('tbody>tr').eq(index + dir).find('td:last a').eq(elIndex);
        for (var i = 0; i < o._list_grids.length; i++) {
            datac[o._list_grids[i]['field'][0]] = _data[i + 1];
        }
        return _datatable_form.call(el, o, dt, param, datac, type);
    };

    // 设置上一条按钮是否可以点击
    if (prevLength) {
        prevEl.removeAttr('disabled').unbind().click(function () {
            return call(-1);
        });
    } else {
        prevEl.attr('disabled', 'disabled');
    }

    // 设置下一条按钮是否可以点击
    if (nextLength) {
        nextEl.removeAttr('disabled').unbind().click(function () {
            return call(1);
        });
    } else {
        nextEl.attr('disabled', 'disabled');
    }

    // 新增表单不显示上一条／下一条按钮,提交成功后关闭弹窗
    if (type == 'add') {
        nextEl.hide();
        prevEl.hide();
        buttonEl.show();
    }
    // 查看详情不显示保存按钮
    else if (type == 'view') {
        nextEl.show();
        prevEl.show();
        buttonEl.hide();
    }
    // 默认是编辑表单，显示全部按钮
    else {
        nextEl.show();
        prevEl.show();
        buttonEl.show();
    }


    // 载入表单
    $.ajax({
        'url': url,
        'type': 'get',
        'success': function (html) {
            try {
                if (!html.status && html.info) {
                    popup.tip(html.info);
                    return false;
                }
            } catch (e) {

            }
            var title = el.text();
            if (param) {
                title += ' [' + (data[param] ? data[param] : param) + ']';
            }
            boxEl.html(html);
            popupId = popup.open({
                content: modalEl
            });
            modalEl.find('.popup-title>span').text(title);
            buttonEl.unbind().click(submitCallback);
            formEl = modalEl.find('.js-form-box form');
            formEl.unbind().submit(submitCallback);
        },
        'error': function () {
            popup.tip('系统异常');
        }
    });

    // 点击保存按钮或者提交表单的回调
    var submitCallback = function () {

        if (ajaxLock) {
            return false;
        }
        var el = buttonEl;
        el.text('保存中...');

        ajaxLock = true;

        $.ajax({
            'url': formEl.attr('action'),
            'data': formEl.serialize(),
            'type': 'post',
            'dataType': 'json',
            'success': function (info) {
                if (info.batch) {
                    var batch_ids = localStorage.getItem('batch_ids');
                    batch_ids = batch_ids ? JSON.parse(batch_ids) : {};
                    batch_ids = $.extend(batch_ids, info.batch);
                    localStorage.setItem('batch_ids', JSON.stringify(batch_ids));
                }

                if (info.status) {
                    popup.close(popupId);
                    if (info.url) {
                        location.href = info.url;
                    } else {
                        dt.ajax.reload(null, false);
                    }
                }
                popup.tip(info.info);
                el.text('保存修改');

            },
            'error': function () {
                alert('系统异常');
                el.text('保存修改');
            },
            'complete': function () {
                el.text('保存修改');
                ajaxLock = false;
            }
        });

        return false;
    };
};

// 显示新增弹窗
var _datatable_add = function (o, dt, param, data) {
    return _datatable_form.call(this, o, dt, param, data, 'add');
}

// 显示预览弹窗
var _datatable_view = function (o, dt, param, data) {
    return _datatable_form.call(this, o, dt, param, data, 'view');
}

// 带确认的批量操作, 用于批量删除等
var _datatable_dels = function (o, dt, param, data) {
    if (__datatable_checks__.call(this)) {
        __datatable_confirms__.call(this, _datatable_dos, o, dt, param, data);
    }
    return false;
}

// 不带确认的批量操作, 用于批量启用/禁用等
var _datatable_dos = function (o, dt, param, data) {
    var ids = __datatable_checks__.call(this);
    if (ids) {
        var query = {
            'ids': ids,
            'param': param
        };
        _datatable_do.call(this, o, dt, param, data, query);
    }
    return false;
}

// 带确认的操作, 用于操作列中的删除
var _datatable_del = function (o, dt, param, data) {
    __datatable_confirms__.call(this, _datatable_do, o, dt, param, data);
    return false;
}

// 不带确认的操作, 用于操作列中启用/禁用等
var _datatable_do = (function () {
    var ajaxLock;
    return function (o, dt, param, data, query) {
        var el = this;
        var url = this.attr('href');
        var seperator = url.search(/\?/) >= 0 ? '&' : '?';
        // 表头按钮调用时传入 query 对象，表格内按钮调用时在这里拼接 query 对象
        if (!query) {
            query = {
                'ids': el.closest('tr').find('input[type="checkbox"]').val(),
                'param': data[param] ? data[param] : param
            };
        }

        if (query.param == '' || query.param == undefined) {
            delete query.param;
        }

        this.attr('disabled', 'disabled');
        $.ajax({
            'url': this.attr('href'),
            'type': 'post',
            'data': query,
            'dataType': 'json',
            'success': function (info) {
                if (info.batch) {
                    var batch_ids = localStorage.getItem('batch_ids');
                    batch_ids = batch_ids ? JSON.parse(batch_ids) : {};
                    batch_ids = $.extend(batch_ids, info.batch);
                    localStorage.setItem('batch_ids', JSON.stringify(batch_ids));
                }

                if (info.status) {
                    dt.ajax.reload(null, false);
                    //modalEl.modal('hide');
                }
                popup.tip(info.info);
            },
            'error': function () {
                popup.tip("系统异常");
            },
            'complete': function () {
                el.removeAttr('disabled');
            }
        });
        return false;
    };
})();

// 跳转
var _datatable_link = function () {
    window.location.href = $(this).attr('href');
    return false;
};

// 跳转(新窗)
var _datatable_blank = function () {
    window.open($(this).attr('href'));
    return false;
};

// 无动作, 用于没有权限的链接
var _datatable_void = function () {
    return false;
};

// 内部方法, 批量操作确认
var __datatable_confirms__ = function (success, o, dt, param, data) {
    var el = $(this);
    var tip = "确认要执行「" + el.text() + "」操作吗？";
    popup.confirm(tip, function () {
        success.call(el, o, dt, param, data);
    });
    return false;
}

// 内部方法, 获取勾选的 checkbox 列表
var __datatable_checks__ = function () {
    var el = this;
    var checked = el.closest('.box').find('table>tbody .ids:checked');
    var ids = [];

    if (!checked.length) {
        popup.tip("请选择要操作的数据");
        return false;
    }

    checked.each(function () {
        ids.push($(this).val());
    });

    return ids.join(',');
}

var _datatable_blank = function () {
    window.open($(this).attr('href'));
    return false;
}


var _datatable_export = function (o, dt, param, data) {
    var request = {};
    var columns = {};
    var form = $('#datatable_blank_form');
    form.children().remove();

    var columns = dt.state().columns;
    var grid, value, v;
    var order = dt.state().order;

    for (var i = 1; i < columns.length; i++) {
        grid = o._list_grids[i - 1];

        if (columns[i].search.search === "") {
            continue;
        }

        form.append($('<input name="columns[' + i + '][search][value]" />').val(columns[i].search.search));
        form.append($('<input name="columns[' + i + '][name]" />').val(grid.field[0]));
        form.append($('<input name="columns[' + i + '][searchable]" />').val('true'));
    }

    if (order[0].length) {
        form.append($('<input name="order[0][column]" value="' + order[0][0] + '">'));
        form.append($('<input name="order[0][dir]" value="' + order[0][1] + '">'));
    }
    form.append($('<input name="start" value="0">'));
    form.append($('<input name="length" value="9999">'));
    form.append($('<input name="fromDataTable" value="1">'));
    form.append($('<input name="ajax" value="1">'));
    form.append($('<input name="_export_" value="1">'));
    form.append($('<input name="_export_type_" >').val(param));
    form.submit();
};